<template>
  <div>
    <!--搜索查询-->
    <el-row>
      <el-col :span="3">&nbsp;</el-col>
      <el-col :span="3"
        ><el-input
          v-model="searchForm.loginName"
          size="mini"
          clearable
          placeholder="请输名称"
        ></el-input
      ></el-col>
      <el-col :span="3"
        ><el-input
          v-model="searchForm.userName"
          size="mini"
          clearable
          placeholder="请输用户名"
        ></el-input
      ></el-col>
      <el-col :span="3"
        ><el-input
          v-model="searchForm.email"
          size="mini"
          clearable
          placeholder="邮箱"
        ></el-input
      ></el-col>
      <el-col :span="3"
        ><el-input
          v-model="searchForm.phonenumber"
          size="mini"
          clearable
          placeholder="电话"
        ></el-input
      ></el-col>
      <el-col :span="3"
        ><el-button
          type="primary"
          size="mini"
          @click="search()"
          icon="el-icon-search"
          >搜索</el-button
        ></el-col
      >
      <el-col :span="3"
        ><el-button
          type="primary"
          size="mini"
          @click="handlerAdd()"
          icon="el-icon-circle-plus"
          >添加</el-button
        ></el-col
      >
      <el-col :span="3"
        ><el-button
          type="primary"
          size="mini"
          v-has="'user:flush'"
          @click="flush()"
          icon="el-icon-refresh"
          >刷新</el-button
        ></el-col
      >
    </el-row>

    <el-row>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="submodule" label="公司名称" width="150">
        </el-table-column>
      
        <el-table-column
          prop="question"
          align="center"
          label="问题"
          width="180"
        >
        </el-table-column>

        <el-table-column prop="answer" label="答案" align="center" width="380">
        </el-table-column>

        <!-- <el-table-column prop="delFlag" :formatter="delFormat" label="删除状态">
        </el-table-column> -->

        <el-table-column label="操作" fixed="right" width="250" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <!--分页插件-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[2, 3, 5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-row>

    <el-row>
      <!--角色授权弹出框-->
      <el-dialog title="角色列表" :visible.sync="rolesVisible">
        <template>
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="checkedRoles"
            @change="handleCheckedRolesChange"
          >
            <el-checkbox
              v-for="role in roleList"
              :label="role.roleId"
              :key="role.roleId"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </template>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addUserAndRole()">确 定</el-button>
        </div>
      </el-dialog>
    </el-row>

    <!--用户添加/更新对话框-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="form" ref="form">
        <el-form-item
          label="所属模块"
          prop="submodule"
          :label-width="formLabelWidth"
        >
          <el-select v-model="form.submodule" placeholder="请选择所属模块">
            <el-option label="服务规则" value="服务规则"></el-option>
            <el-option label="新手上路" value="新手上路"></el-option>
            <el-option label="常见问题" value="常见问题"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="问题"
          prop="question"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.question" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="答案" prop="answer" :label-width="formLabelWidth">
          <el-input v-model="form.answer" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      value: true,
      optionsA: [],
      tableData: [],
      imgUrl: "",
      currentPage: 1, //页码 第几页
      pageSize: 5, //每页显示数量
      total: 100, //总条数
      searchForm: { loginName: "", phonenumber: "", email: "", userName: "" }, //搜索form表单
      title: "问题添加",
      dialogFormVisible: false, //是否显示对话框  默认是不显示
      form: {}, //form表单对象
      formLabelWidth: "120px",
      condition: "",
      rolesVisible: false, //不显示角色列表对话框
      isIndeterminate: true,
      checkAll: false, //是否全选
      checkedRoles: [], //默认选中项
      roleList: [], //有效角色集合
      roleIds: "", //定义选中的所有角色ID集合
      userId: 0, //定义用户ID
    };
  },
  created() {
    //初始化方法 类似于jquery  $({})
    this.loadData();
    var _this = this;
    _this.$http
      .post("/customerIssues/queryByPage", {
        pageNo: this.currentPage,
        pageSize: 100,
        data: {},
      })
      .then(function (response) {
        console.log(JSON.stringify(response));
        if (response.data.code == 200) {
          _this.optionsA = response.data.data.list;
          _this.total = response.data.data.total;
        }
      })
      .catch(function (error) {
        //错误的处理
        // handle error
        console.log(error);
      })
      .then(function () {
        //总执行 最终处理      类似java  异常处理的finally
        // always executed
      });

    //查询所有有效角色，为roleList赋值
    var _this = this;
    this.$http
      .get("/role/queryAll")
      .then(function (response) {
        if (response.data.code == 200) {
          _this.roleList = response.data.data;
        }
      })
      .catch(function (error) {
        console.log(error);
        _this.$message.error("你错了。。。");
      });
  },
  //所有函数
  methods: {
    //加载数据
    loadData() {
      var _this = this;
      //复制 $http官网代码
      // var token  = localStorage.getItem("token");
      _this.$http
        .post("/customerIssues/queryByPage", {
          pageNo: this.currentPage,
          pageSize: this.pageSize,
          data: {
            loginName: this.searchForm.loginName,
            phonenumber: this.searchForm.phonenumber,
            email: this.searchForm.email,
            userName: this.searchForm.userName,
          },
        })
        .then(function (response) {
          if (response.data.code == 200) {
            _this.tableData = response.data.data.list;
            _this.total = response.data.data.total;
          }
        })
        .catch(function (error) {
          console.log(error);
          _this.$message.error("你错了。。。");
        });
    },
    //处理更新
    handleEdit(index, row) {
      var _this = this;
      //row  当前行数据 如果是第一行  row = {deptId:1,deptName:'管理部'把一行数据赋值给form赋值,description:'店长的事',status:1}
      console.log(index, row);
      //显示对话框
      _this.dialogFormVisible = true;
      //指定对话框标题
      _this.title = "问题更新";
      //把一行数据赋值给form赋值
      _this.form = row;
      //把数字1变为字符串1
      _this.form.status = row.status + "";
      _this.imgUrl = row.avatar;
    },
    //处理添加
    handlerAdd() {
      this.imgUrl = "";
      //显示对话框
      this.dialogFormVisible = true;
      //指定对话框标题
      this.title = "问题添加";
      //让form表单重新赋空值
      this.form = {};
    },
    //提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var url = "";
          if (this.title == "问题添加") {
            url = "/customerIssues/add";
          } else {
            url = "/customerIssues/edit";
          }
          //让_this等于当前vue对象
          var _this = this;
          // alert(111);
          //赋值 $http官网代码  this.form =form:{deptName:'',description:'',status:1}
          _this.$http
            .post(url, this.form) //指定请求的url及参数  get
            .then(function (response) {
              //正确返回对象的处理
              // handle success
              //console.log(response);
              //JSON.stringify   把json转换为json字符串，方便查看
              console.log(JSON.stringify(response));
              //直接使用this 会指 $http对象  错误
              // this.tableData
              //判断返回值是否正确
              if (response.data.code == 200) {
                //关闭弹框
                _this.dialogFormVisible = false;
                //提示添加成功
                _this.$message({
                  message: "恭喜你，这是一条成功消息",
                  type: "success",
                });
                //重新加载数据
                _this.loadData();
              } else {
                //错误提示信息
                _this.$message.error("错了哦，这是一条错误消息");
              }
            })
            .catch(function (error) {
              //错误的处理
              // handle error
              console.log(error);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //格式化性别方法
    sexFormat(row, column, cellValue, index) {
      //row当前行数据
      //column 列名称
      //cellValue 列的值
      //index 下标
      //alert(cellValue);
      return cellValue == 0 ? "男" : cellValue == 1 ? "女" : "未知";
      /**  if(cellValue==0){
                    return '男';
                }else if(cellValue==1){
                    return '女';
                }
                return '未知';
               */
    },
    zhFormat(row, column, cellValue, index) {
      //row当前行数据
      //column 列名称
      //cellValue 列的值
      //index 下标
      //alert(cellValue);
      return cellValue == 0 ? "正常" : "异常";
    },
    delFormat(row, column, cellValue, index) {
      //row当前行数据
      //column 列名称
      //cellValue 列的值
      //index 下标
      //alert(cellValue);
      return cellValue == 0 ? "存在" : "消失了";
    },
    //处理每页数量发生变化
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      //让每页数量发生变化
      this.pageSize = val;
      //重载数据
      this.loadData();
    },
    //处理当前页变化
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      //让每页数量发生变化
      this.currentPage = val;
      //重载数据
      this.loadData();
    },
    //查询
    search() {
      this.loadData();
    },
    //刷新
    flush() {
      location.reload();
    },
    //上传前图片类型和大小判断
    beforeAvatarUpload(file) {
      const FILE_NAME = file.name;
      if (
        FILE_NAME.substring(FILE_NAME.lastIndexOf(".")) !== ".bmp" &&
        FILE_NAME.substring(FILE_NAME.lastIndexOf(".")) !== ".jpg" &&
        FILE_NAME.substring(FILE_NAME.lastIndexOf(".")) !== ".png"
      ) {
        this.$message.warning("仅支持.bmp.jpg.png文件");
        return false;
      }
      // const isJPG = file.type === 'image/jpeg';
      const isLt3M = file.size / 1024 / 1024 < 3;

      /* if (!isJPG) {
              this.$message.error('上传头像图片只能是 JPG 格式!');
          }*/
      if (isLt3M) {
        this.file = file;
        return true;
      }
      this.$message.warning("请上传不超过3M的文件.");
      return false;
    },
    handleAvatarSuccess(response, file, fileList) {
      //图片回显
      this.imgUrl = response.data;
      //alert(response);
      //alert(JSON.stringify(response));
      this.form.avatar = response.data;
      // this.form.fileName=file.response.oldFileName;
      // this.form.filePath=file.response.newFilePath;
    },
    //取消按钮
    dialogFormVisiblExit() {
      this.imgUrl = "";
      this.form = "";
      this.dialogFormVisibleAdd = false;
    },
    //处理逻辑删除
    handleDelete(index, row) {
      console.log(index, row);
      //确认框提示
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //让_this等于当前vue对象
          var _this = this;
          // alert(111);
          //赋值 $http官网代码  this.form =form:{deptName:'',description:'',status:1}
          _this.$http
            .get("/user/updateDelFlag?userId=" + row.userId) //指定请求的url及参数  get
            .then(function (response) {
              //正确返回对象的处理
              // handle success
              console.log(response);
              //JSON.stringify   把json转换为json字符串，方便查看
              console.log(JSON.stringify(response));
              //直接使用this 会指 $http对象  错误
              // this.tableData
              //判断返回值是否正确
              if (response.data.code == 200) {
                //提示添加成功
                _this.$message({
                  message: "恭喜你，这是一条成功消息",
                  type: "success",
                });
                //重新加载数据
                _this.loadData();
              } else {
                //错误提示信息
                _this.$message.error("错了哦，这是一条错误消息");
              }
            })
            .catch(function (error) {
              //错误的处理
              // handle error
              console.log(error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //弹出角色列表
    showRoleList(index, row) {
      //获取当前用户ID
      this.userId = row.userId;
      //根据用户ID查询该用户对应的所有角色ID
      var _this = this;
      //复制 axios官网代码
      // var token  = localStorage.getItem("token");
      this.$http
        .get("/role/queryRoleIdsByUserId?userId=" + this.userId)
        .then(function (response) {
          if (response.data.code == 200) {
            //[1,5,6,7]
            _this.checkedRoles = response.data.data;
            //alert(JSON.stringify(_this.checkedRoles))
          }
        })
        .catch(function (error) {
          console.log(error);
          _this.$message.error("你错了。。。");
        });
      //显示角色对话框
      this.rolesVisible = true;
    },
    //处理是否全选中方法
    handleCheckAllChange(val) {
      // alert(val);
      if (val) {
        // alert(JSON.stringify(this.roleList));
        for (var i = 0; i < this.roleList.length; i++) {
          //alert(this.roleList[i].roleId);
          var tempRI = this.roleList[i].roleId;
          this.checkedRoles.push(tempRI);
          this.roleIds += tempRI + ",";
        }
        //去掉最后一个逗号
        this.roleIds = this.roleIds.substr(0, this.roleIds.length - 1);
        // alert(this.roleIds);
      } else {
        this.checkedRoles = [];
        this.roleIds = "";
      }
    },
    //处理重新选择结果
    handleCheckedRolesChange(val) {
      //alert(val);
      //把选中的值赋值给roleIds
      this.roleIds = val;
    },
    //确认，调用后台添加关联
    addUserAndRole() {
      //判断是否有选中的 如果为0，说明没选中
      if (this.roleIds.length == 0) {
        this.$message.error("至少选中一个角色。。。");
        return;
      }
      if (this.userId == 1) {
        var roleIdsArrray = this.roleIds.toString().split(",");
        var tempRoleId = 0;
        //roleIds="1,5,7,8,11,111"
        for (var i = 0; i < roleIdsArrray.length; i++) {
          if (roleIdsArrray[i] == 1) {
            tempRoleId = 1;
            break;
          }
        }
        if (tempRoleId == 0) {
          this.$message.error("管理员必须拥有管理员角色。。。");
          return;
        }
      }
      //保存数据
      var _this = this;
      this.$http
        .get(
          "/role/batchInsertUserRole?userId=" +
            this.userId +
            "&roleIdString=" +
            this.roleIds
        )
        .then(function (response) {
          if (response.data.code == 200) {
            //关闭弹框
            _this.rolesVisible = false;
          }
        })
        .catch(function (error) {
          console.log(error);
          _this.$message.error("你错了。。。");
        });
    }, //修改用户状态（禁用/启用）
    handleChangeStatus(index, row) {
      var _this = this; //复制 $http官网代码 // var token  = localStorage.getItem("token");
      alert(JSON.stringify(row));
      _this.$http
        .post("/user/edit", row)
        .then(function (response) {
          if (response.data.code == 200) {
            //alert("操作成功");
            _this.loadData;
          }
        })
        .catch(function (error) {
          console.log(error);
          _this.$message.error("你错了。。。");
        });
    },
  },
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 178px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
